﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Volo.Abp.AspNetCore.Mvc;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Linq;
using YAPACS.BusinessObjects.Exams;
using YAPACS.BusinessObjects.Managements.Exams;
using YAPACS.Organizations;

namespace YAPACS.RisServer.Controllers;
[Authorize]
[ApiController]
public class ExamCategoryController : AbpControllerBase
{
    private readonly ICurrentUserOrganization _currentUserOrganization;
    private readonly IRepository<ExamCategory, Guid> _examCategoryRepository;
    private readonly IRepository<Exam, Guid> _examRepository;
    private readonly IAsyncQueryableExecuter _asyncQueryableExecuter;

    public ExamCategoryController(IRepository<ExamCategory, Guid> examCategoryRepository, ICurrentUserOrganization currentUserOrganization, IRepository<Exam, Guid> examRepository, IAsyncQueryableExecuter asyncQueryableExecuter)
    {
        _examCategoryRepository = examCategoryRepository;
        _currentUserOrganization = currentUserOrganization;
        _examRepository = examRepository;
        _asyncQueryableExecuter = asyncQueryableExecuter;
    }
    [HttpGet("api/get-exam-categories")]
    public async Task<IActionResult> GetExamCategories([FromQuery]Guid deviceType, [FromQuery]PatientSex? sex)
    {
        var query = await _examCategoryRepository.GetQueryableAsync();
        query = query.Where(e => e.DeviceType.Oid == deviceType && e.Department.Oid == _currentUserOrganization.DepartmentId);
        if (sex == PatientSex.Male)
        {
            query = query.Where(e => e.ApplicableSex != ApplicableSex.Female);
        }
        else if (sex == PatientSex.Female)
        {
            query = query.Where(e => e.ApplicableSex != ApplicableSex.Male);
        }
        var result = await _asyncQueryableExecuter.ToListAsync(query.Select(e => new
        {
            Label = e.Name,
            Value = e.Id
        }));
        return Ok(result);
    }
}
